<!-- roleMgrPage.vue -->
<template>
  <div class="role-mgr-container">
    <el-row>
      <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
        <el-button icon="Plus" @click="createRole()" type="primary">新增角色</el-button>
        <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh; max-width: 1000px;">
        <el-table 
          v-loading="loading" 
          :data="dataList" 
          style="width: 100%; min-width: 600px; height: 100%;"
          @row-click="handleRowClick">
          
          
          
          <el-table-column label="名称" align="center" prop="name" />
          
          <el-table-column label="备注" align="center" prop="remark" />                  
          
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-link :underline="false" type="primary" @click.stop="showDetail(scope.row)">
                详情
              </el-link>           
              <el-link 
                v-if="scope.row.roleId !== 1" 
                :underline="false" 
                type="danger" 
                style="margin-left: 12px;"
                @click.stop="deleteRole(scope.row)">
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
      <pagination 
        v-show="total > 0" 
        :total="total" 
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" 
        @pagination="getList" />
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction'
import { DataPage } from '../../public/network/communicationConverter'
import EventBus from '../../public/engine/ipc/eventBus'
import { deleteRoleDataNetworkCache } from '../../public/network/api'
import { DateUtil } from '../../public/utils/dateUtil'
import { uiNavigation } from '../../public/views/uiEntrance/uiNavigation'

export default {
  name: 'roles',

  data() {
    return {
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      filter: {
        roleName: '',
        roleCode: '',
        status: '',
      },
      dateRange: [],
      dataList: [],
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
    }
  },

  mounted() {
    this.getList()
    EventBus.on('roleDataUpdated', this.getList)
  },

  beforeUnmount() {
    EventBus.off('roleDataUpdated', this.getList)
  },

  methods: {
    async getList() {
      try {
        this.loading = true

        // Update filter with date range
        if (this.dateRange?.length === 2) {
          this.filter.beginTime = this.dateRange[0]
          this.filter.endTime = new Date(this.dateRange[1])
          this.filter.endTime.setHours(23, 59, 59, 999)
        } else {
          this.filter.beginTime = null
          this.filter.endTime = null
        }

        const res = await this.enterpriseMgtUiAction.getRoleData({
          pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
          filter: this.filter
        })

        if (res?.data?.dataList) {
          this.dataList = res.data.dataList
          this.total = res.data.pageInfo?.total || res.data.dataList.length
        } else if (res?.resErr) {
          ElMessage.error('获取角色列表失败: ' + res.resErr)
        }
      } catch (error) {
        console.error('获取角色列表失败', error)
        ElMessage.error('获取角色列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetSearch() {
      this.filter = {
        roleName: '',
        roleCode: '',
        status: '',
      }
      this.dateRange = []
      this.queryParams.pageNum = 1
      this.getList()
    },

    refreshList() {
      deleteRoleDataNetworkCache()
      this.getList()
    },

    createRole() {
      uiNavigation.showRoleDetailPage(this.$router)
    },

    showDetail(row) {
      uiNavigation.showRoleDetailPage(this.$router, { id: row.id, mode: 'edit' })
    },

    editRole(row) {
      uiNavigation.showRoleDetailPage(this.$router, { id: row.id, mode: 'edit' })
    },

    handleRowClick(row) {
      this.showDetail(row)
    },

    async deleteRole(row) {
      try {
        await ElMessageBox.confirm(
          `确定要删除角色【${row.name}】吗?`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const res = await this.enterpriseMgtUiAction.deleteRoleData(row.id)

        if (res != null) {
          ElMessage.success('删除成功')
          this.getList()
        } 
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除操作失败')
        }
      }
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      return DateUtil.getDayTitle(dateStr)
    }
  }
}
</script>

<style scoped>
.role-mgr-container {
  padding-top: 0px;
  padding-left: 20px;
}
</style>